import express from 'express'
import knex from 'knex'
import shortid from 'shortid'

const db = knex({
  client: 'mysql2',
  connection: {
    host: '127.0.0.1',
    port: 3306,
    user: 'root',
    password: 'xxxx',
    database: 'shortlink'
  }
})

const app = express()

app.use(express.json())

app.post('/create_url', async (req,res) => {
  const { url } = req.body
  const short_id = shortid.generate()
  await db('shortlink').insert({
    short_id,
    url
  })
  res.send(`http://localhost:3000/${short_id}`)
})

app.get("/:short_id",async (req,res) => {
  const short_id = req.params.short_id
  const result = await db('shortlink').select('url').where({short_id})
  if (result && result[0]) {
    res.redirect(result[0].url)
  }else {
    res.send('Not Found')
  }
})

app.listen(3000,async () => {
  console.log('服务启动');
})